import React, {useCallback, useEffect, useState} from 'react';
import {Breadcrumb, Button, Form, Input, message, Modal, Space, Table, TableProps} from 'antd';
import {useNavigate} from "react-router-dom";
import type {JobDescription} from "@/types/resp/jobDescription";
import jobDescriptionApi from '@/api/jobDescriptionApi'
import {Result} from "@/types/result";
import {Page} from "@/types/page";
import JobDescriptionAdd from "@/pages/jobDescription/JobDescriptionAdd.tsx";
import JobDescriptionView from "@/pages/jobDescription/JobDescriptionView.tsx";
import EnterpriseSelector from "@/pages/enterprise/EnterpriseSelector.tsx";
import DepartmentSelector from "@/pages/department/DepartmentSelector.tsx";
import { exportToExcel } from '@/utils/exportUtil.ts'
import {getJobTypeText,getJobSalaryRangeText,getJobDescriptionStatusText} from "@/utils/dictTranslator.ts";


const JobDescriptionList: React.FC = () => {

  const navigate = useNavigate();
  const [messageApi, messageContextHolder] = message.useMessage();
  const [modal, modalContextHolder] = Modal.useModal();

  const handleClick = (path: string) => {
    navigate(path);
  };

  const breadcrumbsItems = [
    {title: '首页', className: 'breadcrumbHome', onClick: () => handleClick('/Home')},
    {title: '招聘岗位列表'}
  ]

  const [form] = Form.useForm();

  const onFinish = async () => {
    await onSearch()
  };

  const onReset = () => {
    form.resetFields();
  };

  const [data, setData] = useState<JobDescription[]>([]);
  const onSearch = async () => {
    try {
      const resp: Result<Page<JobDescription>> = await jobDescriptionApi.find(form.getFieldsValue())
      if (resp && resp.code === 1) {
        if (resp.data) {
          const page: Page<JobDescription> = resp.data
          if (page && page.list.length > 0) {
            setData(page.list)
          }
        }
      }
    } catch (e) {
      console.log('获取数据异常', e)
    }
  };

  const columns: TableProps<JobDescription>['columns'] = [
    {title: '企业名称', dataIndex: 'enterpriseName', key: 'enterpriseName', width: 100},
    {title: '岗位名称', dataIndex: 'jobTitle', key: 'jobTitle', width: 120},
    {title: '部门名称', dataIndex: 'departmentName', key: 'departmentName', width: 100},
    {title: '工作地点', dataIndex: 'workLocation', key: 'workLocation', width: 80},
    {title: '岗位类型', key: 'jobType', width: 80, render: (_, record) => (
        <span>
        {(function () {
          if (record.jobType === 10) return '全职';
          else if (record.jobType === 20) return '兼职';
          else if (record.jobType === 30) return '实习';
          else return '未知';
        })()}
      </span>
      ),
    },
    {title: '岗位职责', dataIndex: 'responsibilities', key: 'responsibilities', width: 200, ellipsis: true},
    {title: '岗位要求', dataIndex: 'requirement', key: 'requirement', width: 200, ellipsis: true},
    {title: '薪资范围', key: 'salaryRange', width: 120, render: (_, record) => (
        <span>
        {(function () {
          if (record.salaryRange === 1) return '3000~5000';
          else if (record.salaryRange === 2) return '5001~10000';
          else if (record.salaryRange === 3) return '10001~20000';
          else if (record.salaryRange === 4) return '20001~30000';
          else if (record.salaryRange === 5) return '30000以上';
          else return '未知';
        })()}
      </span>
      ),
    },
    {title: '发布日期', key: 'postingDate', width: 120, render: (_, record) => (
      <div>{record.postingDate ? record.postingDate.format('YYYY-MM-DD') : ''}</div>
    )},
    {title: '截止日期', key: 'closingDate', width: 120, render: (_, record) => (
      <div>{record.closingDate ? record.closingDate.format('YYYY-MM-DD') : ''}</div>
    )},
    {title: '招聘人数', dataIndex: 'headCount', key: 'headCount', width: 80},
    {title: '状态', key: 'status', width: 80, render: (_, record) => (
        <span>
        {(function () {
          if (record.status === 10) return '开放';
          else if (record.status === 20) return '关闭';
          else return '未知';
        })()}
      </span>
      ),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: '250px',
      render: (_, record) => (
        <Space size="middle">
          <Button type="primary" onClick={() => editRow(record.id)}>编辑</Button>
          <Button danger onClick={() => delRow(record.id)}>删除</Button>
          <Button color="primary" variant="outlined" onClick={() => detailRow(record)}>详情</Button>
        </Space>
      ),
    },
  ];

  const [jobDescriptionAddVisible, setJobDescriptionAddVisible] = useState(false);
  const [jobDescriptionViewVisible, setJobDescriptionViewVisible] = useState(false);
  const [selectedJobDescriptionId, setSelectedJobDescriptionId] = useState(0)
  const [selectedJobDescription, setSelectedJobDescription] = useState({})

  const onAdd = () => {
    setSelectedJobDescriptionId(0)
    setJobDescriptionAddVisible(true)
  };

  const editRow = (id: number) => {
    setSelectedJobDescriptionId(id)
    setJobDescriptionAddVisible(true)
  };

  const delRow = useCallback(async (id: number) => {
    const confirmed = await modal.confirm({
      title: '删除提示',
      content: (
        <>
          确定要删除吗?
        </>
      ),
      okText: '确定',
      cancelText: '取消',
      type: 'warning'
    });

    if (confirmed) {
      jobDescriptionApi.del(id)
        .then((resp) => {
          if (resp && resp.code === 1) {
            messageApi.success('删除成功!')
            onSearch()
          } else {
            messageApi.error('操作失败:' + (resp.msg ? resp.msg : '原因未知'))
          }
        })
        .catch(error => {
          console.error('操作失败:', error)
        })
    }
  }, [modal]);

  const detailRow = (record: JobDescription) => {
    setSelectedJobDescription(record)
    setJobDescriptionViewVisible(true)
  };

  const [enterpriseSelectorVisible, setEnterpriseSelectorVisible] = useState(false);
  const findEnterprise = () => {
    setEnterpriseSelectorVisible(true);
  }
  const handleEnterpriseSelected = (selectedEnterprise: { enterpriseId?: number; enterpriseName?: string; }) => {
    setEnterpriseSelectorVisible(false)
    if (selectedEnterprise && 'enterpriseId' in selectedEnterprise) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      enterpriseId: selectedEnterprise['enterpriseId'],
      enterpriseName: selectedEnterprise['enterpriseName'],
      }));
    }
  };
  const handleCloseEnterpriseSelector = () => {
    setEnterpriseSelectorVisible(false)
  };
  const [departmentSelectorVisible, setDepartmentSelectorVisible] = useState(false);
  const findDepartment = () => {
    setDepartmentSelectorVisible(true);
  }
  const handleDepartmentSelected = (selectedDepartment: { departmentId?: number; departmentName?: string; }) => {
    setDepartmentSelectorVisible(false)
    if (selectedDepartment && 'departmentId' in selectedDepartment) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      departmentId: selectedDepartment['departmentId'],
      departmentName: selectedDepartment['departmentName'],
      }));
    }
  };
  const handleCloseDepartmentSelector = () => {
    setDepartmentSelectorVisible(false)
  };

  const handleCloseJobDescriptionAdd = () => {
    setJobDescriptionAddVisible(false)
  };

  const handleCloseJobDescriptionView = () => {
    setJobDescriptionViewVisible(false)
  };

  const onExport = () => {
    const headers = ['企业名称','岗位名称','部门名称','工作地点','岗位类型','岗位职责','岗位要求','薪资范围','发布日期','截止日期','招聘人数','状态']
    jobDescriptionApi.find(form.getFieldsValue()).then(data => {
      if (!data || !data.data || data.data.list.length < 1) {
        messageApi.error('无数据导出')
        return
      }
      const exportData = []
      for (const d of data.data.list) {
        exportData.push([d.enterpriseName,d.jobTitle,d.departmentName,d.workLocation,getJobTypeText(d.jobType),d.responsibilities,d.requirement,getJobSalaryRangeText(d.salaryRange),(d.postingDate ? d.postingDate.format('YYYY-MM-DD') : ''),(d.closingDate ? d.closingDate.format('YYYY-MM-DD') : ''),d.headCount,getJobDescriptionStatusText(d.status)])
      }
      exportToExcel(headers, exportData)
    })
  }

  useEffect(() => {
    onSearch();

    return () => {
    };
  }, []);

  return (
    <div className="jobDescriptionList">
      {messageContextHolder}
      {modalContextHolder}
      <Breadcrumb items={breadcrumbsItems} style={{marginBottom: 'var(--container-margin)'}} />
      <Form form={form} onFinish={onFinish} layout={"inline"}>
        <Form.Item name="enterpriseName" label="企业名称">
          <Input.Search placeholder="请选择企业名称" onSearch={findEnterprise} readOnly={true} />
        </Form.Item>
        <Form.Item name="jobTitle" label="岗位名称">
          <Input maxLength={255} placeholder="请输入岗位名称"/>
        </Form.Item>
        <Form.Item name="departmentName" label="部门名称">
          <Input.Search placeholder="请选择部门名称" onSearch={findDepartment} readOnly={true} />
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">查询</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button onClick={onReset}>重置</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" onClick={onAdd}>新增</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" onClick={onExport}>导出</Button>
        </Form.Item>
      </Form>
      <Table<JobDescription> columns={columns} dataSource={data} size="small" rowKey={record => record.id} pagination={{ position: ["bottomCenter"] }} scroll={{ x: 'true' }} style={{marginTop: 'var(--container-margin)'}} />
      <EnterpriseSelector visible={enterpriseSelectorVisible} onEnterpriseSelected={handleEnterpriseSelected} onCloseEnterpriseSelector={handleCloseEnterpriseSelector} />
      <DepartmentSelector visible={departmentSelectorVisible} onDepartmentSelected={handleDepartmentSelected} onCloseDepartmentSelector={handleCloseDepartmentSelector} />
      <JobDescriptionAdd visible={jobDescriptionAddVisible} onCloseJobDescriptionAdd={handleCloseJobDescriptionAdd} id={selectedJobDescriptionId} />
      <JobDescriptionView visible={jobDescriptionViewVisible} onCloseJobDescriptionView={handleCloseJobDescriptionView} viewRow={selectedJobDescription} />
    </div>
  );
};

export default JobDescriptionList;
